package com.trs.publish.security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.trs.publish.Constants.Constants;
import com.trs.publish.domain.LoginLog;
import com.trs.publish.domain.User;
import com.trs.publish.util.common.IPUtil;

/**
 * @author jia.haihong
 *登陆成功后，记录登陆日志
 */
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {  
	   
	    @Value(value = "${trs.defaultTargetUrl}")
	    private String defaultTargetUrl; 
	   
	    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); 
	    
	    @Override    
		public void onAuthenticationSuccess(HttpServletRequest request,    
		    HttpServletResponse response, Authentication authentication) throws IOException,    
		    ServletException { 
		redirectStrategy.sendRedirect(request, response, this.defaultTargetUrl);          
		super.onAuthenticationSuccess(request, response, authentication);  
		//获得授权后可得到用户信息   可使用SUserService进行数据库操作  
		User user= (User) authentication.getPrincipal();    
		request.getSession().setAttribute("user", user);	
		//添加登录日志
		LoginLog loginLog = new LoginLog();
		loginLog.setUsername(user.getUsername());
		loginLog.setUserid(user.getId());
		String ip =IPUtil.getIp(request);
		loginLog.setIp(ip);
		loginLog.setCreatetime(new Date());
		loginLog.setDepartment(user.getDepartment());
		loginLog.setSfzh(user.getSfzh());
		loginLog.setTruename(user.getTruename());
		loginLog.setSessionid(request.getSession().getId());
		loginLog.setUseragent(request.getHeader("User-Agent"));
		Constants.loginLogQueue.offer(loginLog);
		}    

		
}  